package org.itzheng.itplayer.data

import android.util.Log
import org.itzheng.and.baseutils.json.JsonHelper
import org.itzheng.database.MyDataBaseUtils
import org.itzheng.database.entity.PlayHistory
import org.itzheng.database.entity.PlayListEntity
import org.itzheng.itplayer.bean.VideoInfo
import java.util.*

/**
 * Title:播放数据，比如最近播放列表<br></br>
 * Description: <br></br>
 *
 * @email ItZheng@ZoHo.com
 * Created by itzheng on 2020-12-8.
 */
object DataVideoPlay {
    private const val TAG = "DataVideoPlay"

    /**
     * 将当前播放记录保存
     *
     * @param items
     * @param position
     */
    suspend fun saveLastList(items: ArrayList<VideoInfo>?, position: Int) {
        if (items == null) {
            return
        }
        //保存最后播放记录
        val json = JsonHelper.toJson(items)
        var entities = MyDataBaseUtils.getDataBase().playListEntityDao.queryById(json)

        val entity = PlayListEntity()
        entity.fJsonStr = json
        entity.fPosition = position
        if (!(entities == null || entities.isEmpty())) {
            MyDataBaseUtils.getDataBase().playListEntityDao.delete(entity)
        }
        MyDataBaseUtils.getDataBase().playListEntityDao.insert(entity)

    }

    /**
     * 获取最后播放的列表
     *
     * @return
     */
    suspend fun getLastList(): ArrayList<VideoInfo>? {
        val entities = MyDataBaseUtils.getDataBase().playListEntityDao.query()
        if (entities == null || entities.isEmpty()) {
            return null
        }
        val json = entities[entities.size - 1].fJsonStr
        return JsonHelper.jsonToList(json, VideoInfo::class.java) as ArrayList<VideoInfo>
    }

    /**
     * 播放列表播放的位置
     */
    suspend fun getLastListPosition(): Int {
        val entities = MyDataBaseUtils.getDataBase().playListEntityDao.query()
        if (entities == null || entities.isEmpty()) {
            return 0
        }
        return entities[entities.size - 1].fPosition
    }

    /**
     * 播放记录
     */
    suspend fun savePlayHistory(entity: PlayHistory) {
        if (entity == null) {
            Log.w(TAG, "savePlayHistory:entity==null")
            return
        }
        Log.w(TAG, "savePlayHistory:${JsonHelper.toJson(entity)} ")
        val dao = MyDataBaseUtils.getDataBase().playHistoryDao
        val items = dao.queryById(entity.fPath);
        if (!(items == null || items.isEmpty())) {
            dao.delete(entity)
        }
        dao.insert(entity)
    }

    /**
     * 获取播放记录
     */
    suspend fun getPlayHistory(fPath: String): PlayHistory? {
        if (fPath == null) {
            return null
        }
        val dao = MyDataBaseUtils.getDataBase().playHistoryDao
        val items = dao.queryById(fPath);
        if (items == null || items.isEmpty()) {
            return null
        }
        return items[0]
    }

}